/*
 * Copyright (c) 2007, 2008 Johannes Krampf <Johannes.Krampf@htw-dresden.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "multiplatform.h"
#include "language.h"
#include "conjugation.h"
#include "database.h"
#include "network.h"
#include "general.h"

int listen_sock;

void ExitApplication() {
	closesocket(listen_sock);
#ifdef WIN32
	WSACleanup();
#endif

	ClearLanguages();
	ClearDatabase();
	
	exit(EXIT_SUCCESS);
}

int main(int argc, char** argv) {
	int http_conn;
	struct sockaddr_in their_addr;
	int port = 1500;
	char buffer[8] = "";
	int i;
#ifndef WIN32
	socklen_t sin_size;
#else
	int sin_size;
#endif

	/* Überprüfe die Programmargumente */
	for(i=1;i<argc;i++) {
		if (0 == strncmp("-p", argv[i], 2)) {
			port = atoi(argv[i]+2);
		}else if (0 == strncmp("--port=", argv[i], 7)) {
			port = atoi(argv[i]+7);
		}
		if (0 == strncmp("-d", argv[i], 2)) {
			if (4 >= strlen(argv[i])) {
				strncpy(buffer, argv[i]+2, 2);
				buffer[MinLen(strlen(buffer), 2)] = '\0';
			}
		}else if (0 == strncmp("--database=", argv[i], 11)) {
			if (13 >= strlen(argv[i])) {
				strncpy(buffer, argv[i]+11, 2);
				buffer[MinLen(strlen(buffer), 2)] = '\0';
			}
		}
		if ((0 == strncmp("-h", argv[i], 2)) || (0 == strncmp("--help", argv[i], 6))) {
			printf("Benutzung: %s [OPTIONEN]\n\n", argv[0]);
			printf("Optionen:\n");
			printf("\t-p, --port=\tLege den Port fest.\n");
			printf("\t-d, --database=\tLade eine Datenbank beim Start.\n");
			printf("\t-h, --help\tZeige diese Hilfeseite.\n\n");
			printf("Beispiel:\n");
			printf("\t%s -p1500 -dit\n", argv[0]);
			printf("\t%s --port=1500 --database=it\n\n", argv[0]);
			printf("(c) 2007, 2008 Johannes Krampf\n");
			exit(EXIT_SUCCESS);
		}
	}

	/* Überprüfe den Port */
	if ((0 >= port) || (65535 < port)) {
		fprintf(stderr, "Ungueltiger Port angegeben, nutze 1500.\n");
		port = 1500;
	}else if (1024 > port) {
		fprintf(stderr, "ACHTUNG: Portnummern kleiner als 1024 sind unter Unix nur fuer Root nutzbar.\n");
		fprintf(stderr, "Die Ausfuehrung des Programms als Root wird NICHT empfohlen.\n");
	}

	/* Lade eine Datenbankdatei, wenn angegeben */
	if(0 != strcmp("", buffer)) {
		strcat(buffer, ".dat");
		if (0 != LoadDatabaseFromFile(buffer)) {
			fprintf(stderr, "main: Datenbankdatei %s konnte nicht geladen werden.\n", buffer);
		}
	}

	/* Registriere Dienst unter Windows, Reagiere auf SIGTERM unter *nix */
	InitializeHandlers();

	listen_sock = CreateSocket(port);

	/* Warte auf eingehende Verbindungen */
	while(1) {
		sin_size = sizeof(their_addr);
		http_conn = accept(listen_sock, (struct sockaddr *)&their_addr, &sin_size);
        printf("Verbindung von %s: ", inet_ntoa(their_addr.sin_addr));
		if (-1 == http_conn) {
			perror("accept");
			continue;
		}
		HTTPConnection(http_conn);
	}
	
	return 0;
}
